在 JavaScript 中,Promise 是用來處理非同步操作的一個重要概念。當我們需要處理一些需要時間完成的操作,比如從後端 API 獲取資料,Promise 是非常有用的。
實際應用場景:
當網頁需要讀取後端 API 資料時,我們經常使用 Promise 來抓取遠端資料。
Axios 是一個用於發送 HTTP 請求的函式庫,並且是我第一次接觸前端框架開發時所使用的工具。這個工具語法精簡、易於閱讀,非常適合用來進行 API 請求。
使用 Promise 的基本語法如下:
下面是用React.js 和 Axios 來讀取 JSONPlaceholder API 並顯示資料的範例:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
/** - 資料讀取範例 */
export default function DataFetchingComponent(){
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    // 發送 GET 請求至 JSONPlaceholder API
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        // 處理成功的回應
        setData(response.data);
        setLoading(false);
      })
      .catch(error => {
        // 處理錯誤的情況
        setError(error);
        setLoading(false);
      });
  }, []);  
  if (loading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>Error: {error.message}</div>;
  }
  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map(post => (
          <li key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};